//app.js
var qcloud = require('./vendor/wafer2-client-sdk/index')
var config = require('./config')

let userInfo
let skey

const UNPROMPTED = 0
const UNAUTHORIZED = 1
const AUTHORIZED = 2

App({
  onLaunch: function () {
    qcloud.setLoginUrl(config.service.loginUrl)
  },

  data: {
    locationAuthType: UNPROMPTED
  },

  login({ success, error }) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo'] === false) {
          this.setData({
            locationAuthType: UNAUTHORIZED
          })
          //已拒绝授权
          wx.showModal({
            title: '提示',
            content: '请授权我们获取您的用户信息',
            showCancel: false
          })
        } else {
          this.data.locationAuthType = AUTHORIZED
          this.doQcloudLogin({ success, error })
        }
      }
    })
  },

  doQcloudLogin({ success, error }) {
    qcloud.login({
      success: result => {
        const session = qcloud.Session.get()
        if (result) {
          let userInfo = result
          let skey = session.skey
          success && success({
            userInfo,
            skey
          })
        } else {
          this.getUserInfo({ success, error })
        }
      },
      fail: () => {
        error && error()
      }
    })
  },

  getUserInfo({ success, error }) {
    const session = qcloud.Session.get()

    if (session) {
      success && success({
        userInfo: session.userinfo,
        skey: session.skey
      })
    }
  },

  checkSession({ success, error }) {
    if (userInfo && skey) {
      return success && success({
        userInfo,
        skey
      })
    }
    wx.checkSession({
      success: res => {
        console.log(res)
        this.getUserInfo({
          success: res => {
            userInfo = res.userInfo
            skey = res.skey

            success && success({
              userInfo,
              skey
            })
          },
          fail: () => {
            error && error()
          }
        })
      },
      fail: () => {
        error && error()
      }
    })
  }

})